package de.dhbw.karlsruhe.picsim.model.commands.impl;

import de.dhbw.karlsruhe.picsim.model.actions.ActionFactory;
import de.dhbw.karlsruhe.picsim.model.actions.PicAction;
import de.dhbw.karlsruhe.picsim.model.memory.RegisterValue;
import de.dhbw.karlsruhe.picsim.model.memory.impl.RegisterValueImpl;
import de.dhbw.karlsruhe.picsim.util.Bits;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: goesen
 * Date: May 3, 2010
 * Time: 1:38:19 PM
 */
public class SubWF extends InstructionSupport {
    private static final Log log = LogFactory.getLog(SubWF.class);

    public SubWF(final boolean targetIsWRegister, final Bits argument) {
        super(targetIsWRegister, true, argument);
    }

    @NotNull
    @Override
    protected RegisterValue getValue(@NotNull final RegisterValue addressedFile, @NotNull final RegisterValue wRegister,
                                     @NotNull final List<PicAction> yourActions,
                                     @NotNull final ActionFactory actionFactory) {
        log.debug("Subwf gets executed");
        final int wFile = wRegister.asInteger();
        final int addressedValue = addressedFile.asInteger();
        return subWFgedoenst(yourActions, actionFactory, wFile, addressedValue);
    }

    public static RegisterValue subWFgedoenst(final Collection<PicAction> yourActions,
                                              final ActionFactory actionFactory, final int wFile,
                                              final int addressedValue) {
        final int result = addressedValue - wFile;
        if (result >= 0) {
            log.debug("carry flag will be set");
            yourActions.add(actionFactory.setCarryBit());
        } else {
            log.debug("carry flag will be cleared");
            yourActions.add(actionFactory.clearCarryBit());
        }
        //noinspection UnnecessaryParentheses
        if ((addressedValue % 16) - (wFile % 16) >= 0) {
            log.debug("digit carry will be set");
            yourActions.add(actionFactory.setDigitCarryBit());
        } else {
            yourActions.add(actionFactory.clearDigitCarryBit());
        }


        log.debug("result is " + result);
        return RegisterValueImpl.createUnsafe(result);
    }


}
